<?php

namespace common\base;

use Yii;
use yii\base\NotSupportedException;

/**
 * 用户身份信息基类
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
abstract class User extends BaseUser implements \yii\web\IdentityInterface {

    use \common\traits\Constants;

    const STATUS_DELETED = -1;
    const STATUS_DEFAULT = 0;
    const STATUS_ACTIVE = 10;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DEFAULT, self::STATUS_DELETED]],
        ];
    }

    /**
     * 通过给定ID查找身份 
     * @inheritdoc
     */
    public static function findIdentity($id) {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * 通过给定令牌查找用户身份标识
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null) {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * 通过给定用户名查找用户
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username) {
        return static::findOne([
            'username' => $username,
            'status' => self::STATUS_ACTIVE
        ]);
    }

    /**
     * 根据手机号查询用户信息
     * @param string $mobile
     * @return static|null
     */
    public static function findByMobile($mobile) {
        $entra = Yii::$app->security->generatePrivateKey($mobile);
        return static::findOne([
            'mobile' => $entra,
            'status' => self::STATUS_ACTIVE
        ]);
    }

    /**
     * 通过给定密码重置TOKEN查找用户
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token) {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }
        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * 校验密码重置TOKEN是否有效
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token) {
        if (empty($token)) {
            return false;
        }
        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * 返回可用于检查给定身份ID的有效性的密钥 
     * @inheritdoc
     */
    public function getAuthKey() {
        return $this->auth_key;
    }

    /**
     * 验证给定的AUTH密钥
     * @inheritdoc
     */
    public function validateAuthKey($authKey) {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * 通过哈希验证密码 
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password) {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * 从口令生成哈希密码并将其赋值给当前模型的密码变量
     * @param string $password
     */
    public function setPassword($password) {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * 生成“记住密码”时的认证密钥 
     */
    public function generateAuthKey() {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * 生成新的密码重置令牌
     */
    public function generatePasswordResetToken() {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * 删除密码重置令牌
     */
    public function removePasswordResetToken() {
        $this->password_reset_token = null;
    }

    /**
     * 设置手机号
     * @param string $mobile
     */
    public function setMobile($mobile) {
        /* @var $security \common\base\Security */
        $security = Yii::$app->security;
        $this->mobile = $security->generatePrivateKey($mobile);
    }

    /**
     * 解密手机号
     * @param boolean $mask
     * @return string 手机号
     */
    public function decryptMobile($mask = true) {
        $mobile = Yii::$app->security->decryptMaster('');
        if ($mask !== false) {
            return StringHelper::maskChar($mobile, 3, 2);
        }
        return $mobile;
    }

}
